package io.yizoo.core;

import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.tea.*;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Random;
import java.util.HashSet;
import java.util.Set;

public class AliyunSmsUtil {
   //LTAI5t9N98NGWXi6t7v22y9o
   //eJyvm7D2le9FCqblkSzVBlhDlC3gfX

    private  static String ASC_KEY="yizoo_@_key_0025";
    public static com.aliyun.dysmsapi20170525.Client createClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
                //.setAccessKeyId("LTAI5t9N98NGWXi6t7v22y9o")
                //.setAccessKeySecret("eJyvm7D2le9FCqblkSzVBlhDlC3gfX");
        config.accessKeyId="LTAI5t9N98NGWXi6t7v22y9o";
        config.accessKeySecret="eJyvm7D2le9FCqblkSzVBlhDlC3gfX";
        // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);

    }
    public static void SendSmsTest() throws Exception {
        String[] args_ = {"18860670512", "森诺数智运营平台", "SMS_480250138","3993"};
        java.util.List<String> args = java.util.Arrays.asList(args_);
        com.aliyun.dysmsapi20170525.Client client = AliyunSmsUtil.createClient();
        com.aliyun.dysmsapi20170525.models.SendSmsRequest sendSmsRequest = new com.aliyun.dysmsapi20170525.models.SendSmsRequest()
                .setPhoneNumbers("18860670512")
                .setSignName("阿里云短信测试")
                .setTemplateCode("SMS_154950909")
                .setTemplateParam("{\"code\":\"1234\"}");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            client.sendSmsWithOptions(sendSmsRequest, runtime);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
    }

    public static void SendSmsYZM( String phoneNumber, String yzm){
        try {
            String[] args_ = {phoneNumber, "森诺数智运营平台", "SMS_480250138", "{\"code\":\""+yzm+"\"}"};
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.dysmsapi20170525.Client client = AliyunSmsUtil.createClient();
            SendSmsRequest sendReq = new SendSmsRequest()
                    .setPhoneNumbers(args.get(0))
                    .setSignName(args.get(1))
                    .setTemplateCode(args.get(2))
                    .setTemplateParam(args.get(3));
            SendSmsResponse sendResp = client.sendSms(sendReq);
            String code = sendResp.body.code;
            if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
                System.out.println("SendSmsYZM错误信息: " + sendResp.body.message + "");
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void SendSmsNR( String phoneNumber, String nr){
        try {
            String[] args_ = {phoneNumber, "森诺数智运营平台", "SMS_480250138", "{\"code\":\""+nr+"\"}"};
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.dysmsapi20170525.Client client = AliyunSmsUtil.createClient();
            SendSmsRequest sendReq = new SendSmsRequest()
                    .setPhoneNumbers(args.get(0))
                    .setSignName(args.get(1))
                    .setTemplateCode(args.get(2))
                    .setTemplateParam(args.get(3));
            SendSmsResponse sendResp = client.sendSms(sendReq);
            String code = sendResp.body.code;
            if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
                System.out.println("SendSmsNR错误信息: " + sendResp.body.message + "");
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void SendSmsTask( String phoneNumber, String nr){
        try {
            String[] args_ = {phoneNumber, "森诺数智运营平台", "SMS_480250138", "{\"code\":\""+nr+"\"}"};
            java.util.List<String> args = java.util.Arrays.asList(args_);
            com.aliyun.dysmsapi20170525.Client client = AliyunSmsUtil.createClient();
            SendSmsRequest sendReq = new SendSmsRequest()
                    .setPhoneNumbers(args.get(0))
                    .setSignName(args.get(1))
                    .setTemplateCode(args.get(2))
                    .setTemplateParam(args.get(3));
            SendSmsResponse sendResp = client.sendSms(sendReq);
            String code = sendResp.body.code;
            if (!com.aliyun.teautil.Common.equalString(code, "OK")) {
                System.out.println("SendSmsNR错误信息: " + sendResp.body.message + "");
                return;
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean validatePhoneNumber(String phoneNumber) {
        // 检查是否为空或null
        if (phoneNumber == null || phoneNumber.isEmpty()) {
            return false;
        }

        // 检查是否包含空格
        if (phoneNumber.contains(" ")) {
            return false;
        }

        // 检查长度是否为11
        if (phoneNumber.length() != 11) {
            return false;
        }

        // 检查是否全为数字
        try {
            Long.parseLong(phoneNumber); // 尝试将字符串转换为长整型，如果抛出异常则不是全数字
        } catch (NumberFormatException e) {
            return false;
        }

        // 检查开头数字是否为1
        char firstDigit = phoneNumber.charAt(0);
        if (firstDigit != '1') {
            return false;
        }

        // 检查第二位数字是否在有效范围内（3, 4, 5, 7, 8）
        char secondDigit = phoneNumber.charAt(1);
        if (!"34578".contains(String.valueOf(secondDigit))) {
            return false;
        }

        // 检查是否重复数字（这一步在Java中稍显复杂，因为需要用到Set）
        Set<Character> uniqueDigits = new HashSet<>();
        for (char c : phoneNumber.toCharArray()) {
            uniqueDigits.add(c);
        }
        if (uniqueDigits.size() == 1) {
            return false;
        }

        // 检查特定前缀（可选）
        String[] specificPrefixes = {"130", "131", "132", "133", "134", "135", "136", "137", "138", "139",
                "150", "151", "152", "153", "155", "156", "157", "158", "159",
                "170", "171", "172", "173", "175", "176", "177", "178",
                "180", "181", "182", "183", "184", "185", "186", "187", "188", "189"};
        boolean startsWithValidPrefix = false;
        for (String prefix : specificPrefixes) {
            if (phoneNumber.startsWith(prefix)) {
                startsWithValidPrefix = true;
                break;
            }
        }
        if (!startsWithValidPrefix) {
            return false;
        }

        return true;
    }

    public static String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            code.append(random.nextInt(10)); // 仅生成数字验证码
        }
        return code.toString();
    }

    public static String encrypt(String data){
        try {
            SecretKeySpec secretKey = new SecretKeySpec(ASC_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes());
            return Base64.getEncoder().encodeToString(encryptedBytes);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptedData){
        try {
            SecretKeySpec secretKey = new SecretKeySpec(ASC_KEY.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
